package com.omt.tarjimdinek.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.util.StringUtils;

public class StringHelper {

	/**
	 * Validate hex with regular expression
	 * 
	 * @param hex
	 *            hex for validation
	 * @return true valid hex, false invalid hex
	 */
	public static boolean validate(final String aString, final String aRegex) {

		if (StringUtils.hasLength(aString)) {
			Pattern lPattern = Pattern.compile(aRegex);
			Matcher matcher = lPattern.matcher(aString);
			return matcher.matches();
		}
		return false;
	}

	 /**
     * Check if youtube url is correct and convert url to valid link
     * @return
     */
    public static boolean validateAndConvertYoutubeURL(String aYoutubeURL){
    	return StringUtils.hasLength(aYoutubeURL) && StringHelper.validate(aYoutubeURL, Constant.YOUTUBE_URL);
    }
	
	/**
	 * Encrypt a string with MD5 algorithm
	 * 
	 * @param aString
	 * @return
	 * @throws Exception
	 */
	public static synchronized String encrypt(String aString) throws Exception {
		
		if (StringUtils.hasLength(aString)) {
			byte[] uniqueKey = aString.getBytes();
			byte[] hash = null;
	
			try {
				hash = MessageDigest.getInstance("MD5").digest(uniqueKey);
			} catch (NoSuchAlgorithmException e) {
				throw new Error("No MD5 support in this VM.");
			}
	
			StringBuilder hashString = new StringBuilder();
			for (int i = 0; i < hash.length; i++) {
				String hex = Integer.toHexString(hash[i]);
				if (hex.length() == 1) {
					hashString.append('0');
					hashString.append(hex.charAt(hex.length() - 1));
				} else
					hashString.append(hex.substring(hex.length() - 2));
			}
			return hashString.toString();
		}
		return aString;
	}
	
	public static String encodeToUTF8(String aString){
		if (StringUtils.hasLength(aString)) {
			try {
				return new String(aString.getBytes("ISO-8859-1"), "UTF-8");
			} catch (UnsupportedEncodingException e) {
				return aString;
			}
		}
		return aString;
	}
}
